// 设计原则

// 单一职责（SRP） - proxy
const myImage = (function() {
    const imgNode = document.createElement('img');
    document.body.appendChild(img);
    return {
        setSrc: function(src) {
            imgNode.src = src;
        }
    }
})()

const preloadImg = (function() {
    const img = new Image;
    img.onload = function() {
        myImage.setSrc = this.src;
    }
    return {
        setSrc: function (src) {
            myImage.setSrc('http://loading');
            img.src = src;
        }
    }
})()

// 单一职责（SRP） - 迭代器

const each = function(obj, callback) {
    let value;
    let isArray = Array.isArray(obj);

    if (isArray) {
        for (let i = 0; i < obj.length; i++) {
            callback.call(obj[i], i, obj[i]);
        }
    } else {
        for (let i in obj) {
            value = callback.call(obj[i], i, obj[i]);
        }
    }
}

const appendDiv = function(data) {
    each(data, function(i, n) {
        const div = document.createElement('div');
        div.innerHTML = n;
        document.body.appendChild(div);
    });
}


// 最少知识原则（LKP）
// general.getColonel(c).getMajor(m).getCaptain(c).getSergeant(s).getPrivate(p).diaFoxhole();

// 外观模式

const A = function() {
    a1();
    a2();
}

const B = function() {
    b1();
    b2();
}

const facade = function() {
    A();
    B();
}
facade();

const mult = (function() {
    const cache = {};
    return function() {
        const args = Array.prototype.join.call(arguments, ',');
        if (cache[args]) {
            return cache[args]
        }
        let a = 1;
        for (let i = 0; i < arguments.length; i++) {
            a = a * arguments[i];
        }
        return cache[args] = a;
    }
})()

// 开放-封闭 （OCP）

window.onload = function() {
    // ... code
    console.log(document.getElementsByTagName('*').length);
}

Function.prototype.after = function(afterFn) {
    const self = this;
    return function () {
        const ret = self.apply(this, arguments);
        afterFn.apply(this, arguments);
        return ret;
    }
}

window.onload = (window.onload || function() {}).after(function() {
    console.log(document.getElementsByTagName('*').length);
})


// const makeSound = function(animal) {
//     if (animal instanceof Duck) {
//         console.log('嘎嘎嘎');
//     } else if (animal instanceof Chicken) {
//         console.log('咯咯咯');
//     }
// }

const makeSound = function(animal) {
    animal.sound();
}